/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By www.gzchengguo.cn
* 注意：
* 本软件为www.gzchengguo.cn开发研制，未经购买不得商用
* 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
* 一经发现盗用、分享等行为，将追究法律责任，后果自负
*/
package link.chengguo.orangemall.modules.activity.service.impl;

import cn.hutool.core.util.NumberUtil;
import link.chengguo.orangemall.api.OrangeException;
import link.chengguo.orangemall.common.service.impl.BaseServiceImpl;
import link.chengguo.orangemall.common.utils.QueryHelpPlus;
import link.chengguo.orangemall.dozer.service.IGenerator;
import link.chengguo.orangemall.enums.ShopCommonEnum;
import link.chengguo.orangemall.modules.activity.domain.OrangeStoreSeckill;
import link.chengguo.orangemall.modules.activity.service.OrangeStoreSeckillService;
import link.chengguo.orangemall.modules.activity.vo.StoreSeckillVo;
import link.chengguo.orangemall.modules.activity.service.dto.OrangeStoreSeckillDto;
import link.chengguo.orangemall.modules.activity.service.dto.OrangeStoreSeckillQueryCriteria;
import link.chengguo.orangemall.modules.activity.service.mapper.OrangeStoreSeckillMapper;
import link.chengguo.orangemall.modules.activity.vo.OrangeStoreSeckillQueryVo;
import link.chengguo.orangemall.modules.product.domain.OrangeStoreProductAttrValue;
import link.chengguo.orangemall.modules.product.service.OrangeStoreProductAttrService;
import link.chengguo.orangemall.modules.product.service.OrangeStoreProductReplyService;
import link.chengguo.orangemall.modules.product.vo.OrangeStoreProductAttrQueryVo;
import link.chengguo.orangemall.utils.FileUtil;
import link.chengguo.orangemall.utils.OrderUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


/**
* @author chengguo
* @date 2020-05-13
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class OrangeStoreSeckillServiceImpl extends BaseServiceImpl<OrangeStoreSeckillMapper, OrangeStoreSeckill> implements OrangeStoreSeckillService {

    @Autowired
    private IGenerator generator;

    @Autowired
    private OrangeStoreSeckillMapper orangeStoreSeckillMapper;

    @Autowired
    private OrangeStoreProductReplyService replyService;

    @Autowired
    private OrangeStoreProductAttrService orangeStoreProductAttrService;


    /**
     * 退回库存减少销量
     * @param num 数量
     * @param seckillId 秒杀产品id
     */
    @Override
    public void incStockDecSales(int num, Long seckillId) {
        orangeStoreSeckillMapper.incStockDecSales(num,seckillId);
    }

    /**
     * 减库存增加销量
     * @param num 数量
     * @param seckillId 秒杀产品id
     */
    @Override
    public void decStockIncSales(int num, Long seckillId) {
        int res = orangeStoreSeckillMapper.decStockIncSales(num,seckillId);
        if(res == 0) {
            throw new OrangeException("秒杀产品库存不足");
        }
    }

//    @Override
//    public OrangeStoreSeckill getSeckill(int id) {
//        QueryWrapper<OrangeStoreSeckill> wrapper = new QueryWrapper<>();
//        int nowTime = OrderUtil.getSecondTimestampTwo();
//        wrapper.eq("id",id).eq("is_del",0).eq("status",1)
//                .le("start_time",nowTime).ge("stop_time",nowTime);
//        return orangeStoreSeckillMapper.selectOne(wrapper);
//    }

    /**
     * 产品详情
     * @param id 砍价商品id
     * @return StoreSeckillVo
     */
    @Override
    public StoreSeckillVo getDetail(Long id){
        Date now = new Date();
        OrangeStoreSeckill storeSeckill = this.lambdaQuery().eq(OrangeStoreSeckill::getId,id)
                .eq(OrangeStoreSeckill::getStatus, ShopCommonEnum.IS_STATUS_1.getValue())
                .eq(OrangeStoreSeckill::getIsShow,ShopCommonEnum.SHOW_1.getValue())
                .le(OrangeStoreSeckill::getStartTime,now)
                .ge(OrangeStoreSeckill::getStopTime,now)
                .one();

        if(storeSeckill == null){
            throw new OrangeException("秒杀产品不存在或已下架");
        }
        //获取商品sku
        Map<String, Object> returnMap = orangeStoreProductAttrService.getProductAttrDetail(storeSeckill.getProductId());


        return StoreSeckillVo.builder()
                .productAttr((List<OrangeStoreProductAttrQueryVo>)returnMap.get("productAttr"))
                .productValue((Map<String, OrangeStoreProductAttrValue>)returnMap.get("productValue"))
                .storeInfo(generator.convert(storeSeckill, OrangeStoreSeckillQueryVo.class))
                .reply(replyService.getReply(storeSeckill.getProductId()))
                .replyCount(replyService.productReplyCount(storeSeckill.getProductId()))
                .build();
    }

    /**
     * 秒杀产品列表
     * @param page page
     * @param limit limit
     * @return list
     */
    @Override
    public List<OrangeStoreSeckillQueryVo> getList(int page, int limit, int time) {
        Date nowTime = new Date();
        Page<OrangeStoreSeckill> pageModel = new Page<>(page, limit);
        QueryWrapper<OrangeStoreSeckill> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(OrangeStoreSeckill::getStatus, ShopCommonEnum.IS_STATUS_1.getValue())
                .eq(OrangeStoreSeckill::getTimeId,time)
                .le(OrangeStoreSeckill::getStartTime,nowTime)
                .ge(OrangeStoreSeckill::getStopTime,nowTime)
                .orderByDesc(OrangeStoreSeckill::getSort);
        List<OrangeStoreSeckillQueryVo> orangeStoreSeckillQueryVos = generator.convert
               (orangeStoreSeckillMapper.selectPage(pageModel,wrapper).getRecords(),
                       OrangeStoreSeckillQueryVo.class);
        orangeStoreSeckillQueryVos.forEach(item->{
            Integer sum = item.getSales() + item.getStock();
            item.setPercent(NumberUtil.round(NumberUtil.mul(NumberUtil.div(item.getSales(),sum),
                    100),0).intValue());
        });
        return orangeStoreSeckillQueryVos;
    }

    @Override
    //@Cacheable
    public Map<String, Object> queryAll(OrangeStoreSeckillQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<OrangeStoreSeckill> page = new PageInfo<>(queryAll(criteria));
        List<OrangeStoreSeckillDto> storeSeckillDTOS = generator.convert(page.getList(), OrangeStoreSeckillDto.class);
        for (OrangeStoreSeckillDto storeSeckillDTO : storeSeckillDTOS){
            String statusStr = OrderUtil.checkActivityStatus(storeSeckillDTO.getStartTime(),
                    storeSeckillDTO.getStopTime(), storeSeckillDTO.getStatus());
            storeSeckillDTO.setStatusStr(statusStr);
        }
        Map<String,Object> map = new LinkedHashMap<>(2);
        map.put("content",storeSeckillDTOS);
        map.put("totalElements", page.getTotal());
        return map;
    }


    @Override
    //@Cacheable
    public List<OrangeStoreSeckill> queryAll(OrangeStoreSeckillQueryCriteria criteria){
        return baseMapper.selectList(QueryHelpPlus.getPredicate(OrangeStoreSeckill.class, criteria));
    }


    @Override
    public void download(List<OrangeStoreSeckillDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (OrangeStoreSeckillDto orangeStoreSeckill : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("推荐图", orangeStoreSeckill.getImage());
            map.put("轮播图", orangeStoreSeckill.getImages());
            map.put("活动标题", orangeStoreSeckill.getTitle());
            map.put("简介", orangeStoreSeckill.getInfo());
            map.put("价格", orangeStoreSeckill.getPrice());
            map.put("成本", orangeStoreSeckill.getCost());
            map.put("原价", orangeStoreSeckill.getOtPrice());
            map.put("返多少积分", orangeStoreSeckill.getGiveIntegral());
            map.put("排序", orangeStoreSeckill.getSort());
            map.put("库存", orangeStoreSeckill.getStock());
            map.put("销量", orangeStoreSeckill.getSales());
            map.put("单位名", orangeStoreSeckill.getUnitName());
            map.put("邮费", orangeStoreSeckill.getPostage());
            map.put("内容", orangeStoreSeckill.getDescription());
            map.put("开始时间", orangeStoreSeckill.getStartTime());
            map.put("结束时间", orangeStoreSeckill.getStopTime());
            map.put("产品状态", orangeStoreSeckill.getStatus());
            map.put("是否包邮", orangeStoreSeckill.getIsPostage());
            map.put("热门推荐", orangeStoreSeckill.getIsHot());
            map.put("最多秒杀几个", orangeStoreSeckill.getNum());
            map.put("显示", orangeStoreSeckill.getIsShow());
            map.put("时间段id", orangeStoreSeckill.getTimeId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
